package org.abac4j.el;

import java.lang.reflect.Method;
import java.util.Map;

import javax.el.FunctionMapper;
import javax.el.ValueExpression;
import javax.el.VariableMapper;

import org.jboss.el.ExpressionFactoryImpl;
import org.jboss.el.ValueExpressionLiteral;
import org.jboss.el.lang.EvaluationContext;
import org.jboss.el.lang.FunctionMapperImpl;
import org.jboss.el.lang.VariableMapperImpl;

public class JbossELService implements ExpressionLanguageService {
	
	public FunctionMapper buildFunctionMapper(Map<String, Method> functionMethodMap){
		FunctionMapperImpl mapper = new FunctionMapperImpl();
		for(String functionName : functionMethodMap.keySet()){
			mapper.addFunction("", functionName, functionMethodMap.get(functionName));
		}
		return mapper;
	}
	
	public VariableMapper buildVariableMapper(Map<String, Object> attributeMap){
		VariableMapperImpl mapper = new VariableMapperImpl();
		for(String attributeName : attributeMap.keySet()){
			ValueExpressionLiteral expression = new ValueExpressionLiteral(
					attributeMap.get(attributeName), 
					attributeMap.get(attributeName).getClass());
			mapper.setVariable(attributeName, expression);
		}
		return mapper;
	}
	
	public EvaluationContext buildEvaluationContext(Map<String, Method> functionMethodMap, Map<String, Object> attributeMap) {
		return new EvaluationContext(null, buildFunctionMapper(functionMethodMap), buildVariableMapper(attributeMap));
	}
	
	public Boolean evaluateBooleanExpression(EvaluationContext elContext, String expression){
		ValueExpression result = new ExpressionFactoryImpl().createValueExpression(elContext, expression, Boolean.class);
		return (Boolean) result.getValue(elContext);
	}
}